//
//  JCSetClubPasswordVC.m
//  SquashSpark
//
//  Created by 郭吉成 on 2017/12/6.
//  Copyright © 2017年 Coollang-YF. All rights reserved.
//

#import "JCSetClubPasswordVC.h"
#import "JCClubApi.h"

@interface JCSetClubPasswordVC ()<UITextFieldDelegate>

@property (strong, nonatomic) IBOutletCollection(UILabel) NSArray *showLabels;
@property (weak, nonatomic) IBOutlet UITextField *passInput;
@property (weak, nonatomic) IBOutlet UIButton *button;
@property (strong, nonatomic) NSString *password;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *bottomConstraint;

@end

@implementation JCSetClubPasswordVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initCode];
}

- (void)initCode{
    for (UILabel *label in _showLabels) {
        label.layer.borderColor = [UIColor whiteColor].CGColor;
        label.layer.borderWidth = 2;
        label.text = @"-";
    }
    _button.layer.cornerRadius = 3;
    _button.layer.masksToBounds = YES;
    [_passInput becomeFirstResponder];
    self.navigationItem.title = @"Setting Password";
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}

- (void)keyBoardWillShow:(NSNotification *)notification{
    //获取键盘的高度
    NSDictionary *userInfo = [notification userInfo];
    NSValue *value = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = [value CGRectValue];
    int height = keyboardRect.size.height;
    CGFloat time = [[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
    
    _bottomConstraint.constant = height + 10;
    [UIView animateKeyframesWithDuration:time delay:0 options:UIViewKeyframeAnimationOptionCalculationModePaced animations:^{
        [self.view layoutIfNeeded];
    } completion:^(BOOL finished) {
        
    }];
}

- (void)keyBoardWillHide:(NSNotification *)noti{
    _bottomConstraint.constant = 50;
    [UIView animateKeyframesWithDuration:.5 delay:0 options:UIViewKeyframeAnimationOptionCalculationModePaced animations:^{
        [self.view layoutIfNeeded];
    } completion:^(BOOL finished) {

    }];
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    NSString *inputString = [textField.text stringByReplacingCharactersInRange:range withString:string];
    if (inputString.length >= 5) {
        [_button setTitle:@"SAVE" forState:UIControlStateNormal];
    }else{
         [_button setTitle:@"RESET" forState:UIControlStateNormal];
    }
    
    if (inputString.length > 5) {
        return NO;
    }else{
        [self showPass:inputString];
        return YES;
    }
}

- (void)showPass:(NSString *)pass {
    NSMutableArray *passBuffer = @[@"-",@"-",@"-",@"-",@"-"].mutableCopy;
    UILabel *showLabel;
    _password = nil;
    for (NSInteger i = 0; i < pass.length; i++) {
        [passBuffer replaceObjectAtIndex:i withObject:[pass substringWithRange:NSMakeRange(i, 1)]];
    }
    for (NSInteger i = 0; i < passBuffer.count; i++) {
        for (UILabel *label in _showLabels) {
            if (label.tag == i) {
                showLabel = label;
            }
        }
        showLabel.text = passBuffer[i];
        if (!_password) {
            _password = passBuffer[i];
        }else{
            _password = [_password stringByAppendingString:passBuffer[i]];
        }
    }
}

- (IBAction)buttonAction:(UIButton *)sender {
    __weak typeof(self)weakSelf = self;
    NSString *title = [sender titleForState:UIControlStateNormal];
    if ([title isEqualToString:@"SAVE"]) {
        NSLog(@"提交密码：%@",_password);
        if (_password && ![_password containsString:@"-"]) {
            [self.hud showWithMaskType:WSProgressHUDMaskTypeClear];
            [JCClubApi setClubPasswordWithClubID:_clubID password:_password complete:^(NSError *error) {
                if (error) {
                    [weakSelf.hud showErrorWithString:error.domain dimissAfterSecond:2];
                }else{
                    [weakSelf.hud showSuccessWithStatus:@"Success" dimissAfterSecond:2];
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        [weakSelf.navigationController popViewControllerAnimated:YES];
                    });
                }
            }];
        }
    }else{
        for (UILabel *label in _showLabels) {
            label.text = @"-";
        }
        [sender setTitle:@"SAVE" forState:UIControlStateNormal];
        _passInput.text = @"";
        _password = nil;
    }
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
